/*
 * @Author: yangzonglong
 * @Date: 2021-03-09 16:03:48
 * @version: v1.0.0
 * @Descripttion: 列
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-16 17:46:54
 * @Auditor:
 */
import React, { useCallback } from 'react';
import uuid from 'uuid-v4';
import { Form, Dropdown, Menu, Button } from 'antd';
import update from 'immutability-helper';
import ColumnItem from './ColumnItem';
import Icon from '../../icon/Icon';
import { ColumnType, menus } from './../config';
import styles from './style.module.scss';

const FormItem = Form.Item,
  MenuItem = Menu.Item;
// ,
// dataSourceKey = 'columns';

const createDataItem = (dataSource: ColumnType[], type: string) => {
  const curTotal = dataSource.length + 1;

  return {
    title: '未命名' + curTotal,
    dataIndex: 'dataIndex' + curTotal + Math.ceil(Math.random() * 1000),
    width: 200,
    key: uuid(),
    type: type,
    options:
      type === 'checkbox' || type === 'radio' || type === 'select'
        ? {
          dataSource: [
            {
              label: '未命名1',
              value: 'Value 1',
              key: uuid(),
            },
            {
              label: '未命名2',
              value: 'Value 2',
              key: uuid(),
            },
            {
              label: '未命名3',
              value: 'Value 3',
              key: uuid(),
            },
          ],
        }
        : type === 'datePicker'
          ? { format: 'YYYY/MM/DD' }
          : {},
  };
};

interface IProps {
  changeControlProps(k: string, value: any, mergeOptions?: boolean): void;
  setCurColumn(column: ColumnType): void;
  options?: {
    columns?: ColumnType[];
    showItemNo?: boolean;
  };
}

const Columns = ({ options, changeControlProps, setCurColumn }: IProps) => {
  const columns = options?.columns || [];

  const remove = useCallback(
    (index: number) => {

      let _list: any = [];
      if (columns[index]['type'] === "dataLink") {
        let key = columns[index]?.['key'];

        _list = columns.map(item => {
          if (item.type === 'input' && item?.options?.bindName === key) {
            return { ...item, options: { ...item.options, bindName: undefined, showFiled: undefined } };
          } else if (item.type === 'dataLinkCombox' && item?.options?.bindName === key) {
            return { ...item, options: { ...item.options, bindName: undefined, screenConditionRules: [] } };
          } else {
            return item;
          }
        });

      } else {
        _list = [...columns];
      }

      changeControlProps(
        'tableProps',
        update(options, {
          showItemNo: {
            $set: options?.showItemNo,
          },
          columns: {
            $set: update(_list, {
              $splice: [[index, 1]],
            }),
          },
        }),
        true
      );
    },
    [changeControlProps, columns, options]
  );

  const change = useCallback(
    (index: number, k: string, v: string) => {
      changeControlProps(
        'tableProps',
        update(options, {
          showItemNo: {
            $set: options?.showItemNo,
          },
          columns: {
            $set: update(columns, {
              [index]: {
                [k]: {
                  $set: v,
                },
              },
            }),
          },
        }),
        true
      );
    },
    [changeControlProps, columns, options]
  );

  const add = useCallback(
    (e) => {
      changeControlProps(
        'tableProps',
        update(options, {
          showItemNo: {
            $set: options?.showItemNo,
          },
          columns: {
            $set: update(columns, {
              $push: [createDataItem(columns, e.key)],
            }) as any,
          },
        }),
        true
      );
    },
    [changeControlProps, columns, options]
  );

  const move = useCallback(
    (draggedId: string, hoverId: string) => {
      let draggedIndex: number = 0,
        hoverIndex: number = 0;

      columns.forEach((item, index) => {
        if (item.key === draggedId) draggedIndex = index;
        if (item.key === hoverId) hoverIndex = index;
      });

      changeControlProps(
        'tableProps',
        update(options, {
          showItemNo: {
            $set: options?.showItemNo,
          },
          columns: {
            $set: update(columns, {
              $splice: [
                [draggedIndex, 1],
                [hoverIndex, 0, columns[draggedIndex]],
              ],
            }),
          },
        }),
        true
      );
    },
    [changeControlProps, columns, options]
  );
  console.log(columns);

  return (
    <>
      <FormItem label="表格字段">
        <ul className={styles.options}>
          {columns.map((item, i) => (
            <ColumnItem remove={remove} change={change} move={move} originalIndex={i} key={item.key} setCurColumn={setCurColumn} item={item} />
          ))}
        </ul>

        <p />
        <Dropdown
          trigger={'click' as any}
          placement='bottomCenter'
          overlay={
            <Menu
              className={styles.menuHeight}
              onClick={add}>
              {menus.map((item) => (
                <MenuItem key={item.controlType}>{item.text}</MenuItem>
              ))}
            </Menu>
          }
        >
          <Button className={styles.btnStyle} icon={<Icon icon="&#xe635;" />} block>
            添加新选项
          </Button>
        </Dropdown>
      </FormItem>
    </>
  );
};

export default Columns;
